package com.itheima.web;

import com.itheima.bean.User;
import com.itheima.common.R;
import com.itheima.service.UserService;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/getcode")
    public R getcode(String phone){
        String s = ValidateCodeUtils.generateValidateCode4String(4);
        redisTemplate.opsForValue().set("VALIDATE_CODE"+phone,s,5, TimeUnit.MINUTES);
//        session.setAttribute(phone,s);
//        SMSUtils.sendMessage("发送者","发送模板",phone,s);
        return R.success(s);
    }
    @PostMapping("/login")
    public R login(@RequestBody Map<String,String>map, HttpSession session){
        String phone = map.get("phone");
        String code1 = map.get("code");
//        String code2 = (String) session.getAttribute(phone);
        String code2 = (String) redisTemplate.opsForValue().get("VALIDATE_CODE" + phone);
        if (code2!=null&&code2.equalsIgnoreCase(code1)){
            User user = userService.findByphone(phone);
            if (user!=null){
                session.setAttribute("user",user);
                redisTemplate.delete("VALIDATE_CODE" + phone);
                return R.success("登录成功！");
            }
            User user1 = new User();
            user1.setPhone(phone);
            user1.setName("reggie"+phone);
            if (userService.add(user1)>0){
                session.setAttribute("user",user1);
                redisTemplate.delete("VALIDATE_CODE" + phone);
                return R.success("登录成功！");
            }
        }
        return R.error("登录失败！");
    }
}
